<template>
  <div class="father">
    <el-container class="el-container">
      <el-aside width="200px"></el-aside>
      <el-main>
        <el-card>
          <el-row
            ><span
              >Please enter your activity title<span class="red-asterisk">
                *</span
              ></span
            ></el-row
          >
          <el-row class="content">
            <el-input v-model="form.title" placeholder="请输入内容"></el-input>
          </el-row>

          <el-row
            ><span>Tags<span class="red-asterisk"> *</span></span></el-row
          >

          <el-row class="content">
            <el-select
              v-model="form.tags"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="请输入标签，按回车确认"
              style="width: 100%"
            >
              <el-option
                v-for="item in existingTags"
                :key="item"
                :label="item"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-row>

          <el-row>
            <span>
              选择封面图片(最多选择一张)
              <span class="red-asterisk"> *</span>
            </span>
          </el-row>
          <el-row class="content">
            <el-upload
              action="http://localhost:8081/activities/upload"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :on-success="handleUploadSuccess"
              :limit="1"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible" size="tiny">
              <img width="100%" :src="dialogImageUrl" alt="" />
            </el-dialog>
          </el-row>

          <el-row
            ><span>金额<span class="red-asterisk"> *</span></span></el-row
          >
          <el-row class="content">
            <el-input-number
              v-model="form.money"
              :min="0"
              :max="100000"
              placeholder="请输入金额"
              style="width: 100%"
            >
            </el-input-number>
          </el-row>

          <el-row
            ><span
              >最大参与人数<span class="red-asterisk"> *</span></span
            ></el-row
          >
          <el-row class="content">
            <el-input-number
              v-model="form.maxParticipants"
              :min="1"
              :max="999"
              placeholder="请输入最大参与人数"
              style="width: 100%"
            >
            </el-input-number>
          </el-row>

          <el-row
            ><span
              >Please enter a description<span class="red-asterisk">
                *</span
              ></span
            ></el-row
          >
          <el-row class="content">
            <div ref="quillEditor" class="quill-editor"></div>
            <!-- Quill 编辑器 -->
          </el-row>
          <el-row class="word-count">{{ wordCount }}/{{ maxWordCount }}</el-row>

          <el-row><span></span></el-row>

          <el-row>
            <div
              style="
                height: 1px;
                width: 100%;
                margin-bottom: 10px;
                background-color: rgb(128, 128, 128);
              "
            ></div>
          </el-row>

          <el-row>
            <el-col :span="8">
              <el-button
                @click="resetForm"
                style="
                  width: 100%;
                  background-color: #1f2d3d;
                  color: white;
                  font-weight: bold;
                "
                >RESET
              </el-button>
            </el-col>
            <el-col :span="8" :offset="8">
              <el-button
                @click="submitForm"
                style="
                  width: 100%;
                  background-color: #ffbd00;
                  color: black;
                  font-weight: bold;
                "
                >SUBMIT
              </el-button>
            </el-col>
          </el-row>
        </el-card>
      </el-main>

      <el-aside
        class="el-aside-right"
        width="200px"
        style="background-color: transparent"
      ></el-aside>
    </el-container>
  </div>
</template>

<script>
import Quill from "quill";
import "quill/dist/quill.snow.css";
import { postRequest } from "@/api/request";

export default {
  data() {
    return {
      wordCount: 0,
      maxWordCount: 2000,
      form: {
        title: "",
        description: "",
        tags: [],
        imageSrc: "",
        maxParticipants: 1,
        money: 0,
      },
      dialogImageUrl: "",
      dialogVisible: false,
      existingTags: ["活动", "讲座", "比赛", "志愿者"],
    };
  },
  methods: {
    handlePreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleRemove(file, fileList) {
      // this.form.fileList = fileList;
    },
    handleSuccess(response, file, fileList) {
      // this.form.fileList = fileList;
    },
    async submitForm() {
      this.form.description = this.quill.root.innerHTML;
      console.log("Form submitted:", this.form);

      try {
        const response = await postRequest("/jobs", {
          title: this.form.title,
          description: this.form.description,
          tags: this.form.tags,
          imageSrc: this.form.imageSrc,
          maxParticipants: this.form.maxParticipants,
          money: this.form.money,
        });

        console.log("Server response:", response.data);
        this.$message({
          message: "上传成功",
          type: "success",
        });
      } catch (error) {
        console.error("Error submitting form:", error);
        this.$message.error("上传失败");
      }
    },
    resetForm() {
      this.form.title = "";
      this.quill.root.innerHTML = "";
      this.clearEditor();
    },
    initializeQuill() {
      const initialHeight = 200; // 初始高度
      this.$refs.quillEditor.style.height = `${initialHeight}px`; // 设置初始高度

      const editor = this.$refs.quillEditor;
      // 初始化 Quill 编辑器
      this.quill = new Quill(editor, {
        theme: "snow", // 使用 snow 主题
        placeholder: "   请输入描述...", // 默认显示的提示文字
        modules: {
          toolbar: [
            [{ header: "1" }, { header: "2" }, { font: [] }],
            [{ list: "ordered" }, { list: "bullet" }],
            ["bold", "italic", "underline"],
            [{ align: [] }],
            ["link"],
            ["image"],
          ],
        },
      });

      this.quill.on("text-change", () => {
        this.updateWordCount();
        this.adjustHeight(initialHeight);
      });
    },
    adjustHeight(initialHeight) {
      // 获取编辑器的内容容器
      const editorContent = this.$refs.quillEditor.querySelector(".ql-editor");
      if (editorContent) {
        // 使用 Quill 的 getContents 方法获取 Delta 格式的内容
        const delta = this.quill.getContents();

        // 初始化内容高度，基于初始高度
        let contentHeight = initialHeight;

        // 遍历 Delta 内容
        delta.ops.forEach((op) => {
          if (typeof op.insert === "string") {
            // 按每行的高度累计（假设每行约 20px 高度）
            const lines = op.insert.split("\n").length - 1;
            contentHeight += lines * 20; // 可根据实际行高调整
          } else if (op.insert.image) {
            // 为每张图片追加固定高度（假设图片占 150px 高度）
            contentHeight += 350; // 可根据实际图片大小调整
          }
        });

        // 如果计算的内容高度大于初始高度，则调整编辑器高度
        if (contentHeight > initialHeight) {
          this.$refs.quillEditor.style.height = `${contentHeight}px`;
        }
      }
    },
    updateWordCount() {
      const text = this.quill.getText().trim(); // 获取 Quill 编辑器内容
      console.log("Text:", text);
      this.wordCount =
        text.length > this.maxWordCount ? this.maxWordCount : text.length; // 限制最大字数
    },
    clearEditor() {
      this.quill.setText(""); // 清空编辑器内容
      this.updateWordCount(); // 更新字数统计
    },
    handlePictureCardPreview(file) {
      console.log("url是", file.url);
      this.dialogimageSrc = file.url;
      this.dialogVisible = true;
    },
    handleUploadSuccess(response, file, fileList) {
      // this.form.fileList = fileList;
      // 拼接完整的图片URL
      const fullimageSrc = `http://localhost:8081${response}`;
      console.log("完整的图片URL:", fullimageSrc);

      // 保存到 form 数据中，以便后续提交使用
      this.form.imageSrc = fullimageSrc;
    },
  },
  mounted() {
    // 在 mounted 生命周期钩子中初始化 Quill 编辑器
    this.initializeQuill();
  },
};
</script>

<style scoped>
.content {
  margin-bottom: 70px;
}

.red-asterisk {
  color: red;
}

.quill-editor {
  border: 1px solid #ddd;
  overflow: hidden; /* 防止内容超出容器 */
  transition: height 0.2s ease; /* 平滑调整高度 */
}

.word-count {
  text-align: right;
  margin-top: -70px;
  margin-bottom: 50px;
}
</style>
